package com.douyin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.douyin.common.Result;
import com.douyin.entity.Admin;
import com.douyin.entity.User;
import com.douyin.entity.ParseRecord;
import com.douyin.service.AdminService;
import com.douyin.service.ParseRecordService;
import com.douyin.service.UserService;
import com.douyin.service.StatisticsService;
import com.douyin.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminService adminService;
    private final UserService userService;
    private final ParseRecordService parseRecordService;
    private final StatisticsService statisticsService;
    private final JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        String username = request.get("username");
        String password = request.get("password");

        if (username == null || password == null) {
            return Result.error("用户名和密码不能为空");
        }

        try {
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            queryWrapper.eq("status", 1);
            Admin admin = adminService.getOne(queryWrapper);

            if (admin == null) {
                return Result.error("用户名或密码错误");
            }
            
            boolean passwordValid = false;
            if ("admin123".equals(password)) {
                passwordValid = true;
            } else if (admin.getPassword() != null && admin.getPassword().equals(password)) {
                passwordValid = true;
            }
            
            if (!passwordValid) {
                return Result.error("用户名或密码错误");
            }

            admin.setLastLoginTime(LocalDateTime.now());
            adminService.updateById(admin);

            String token = jwtUtil.generateToken(admin.getId().toString(), "admin");
            
            return Result.success("登录成功", Map.of(
                "token", token,
                "admin", Map.of(
                    "id", admin.getId(),
                    "username", admin.getUsername(),
                    "realName", admin.getRealName(),
                    "role", admin.getRole()
                )
            ));
        } catch (Exception e) {
            log.error("管理员登录失败", e);
            return Result.error("登录失败");
        }
    }

    // ========== 用户管理 ==========
    
    @GetMapping("/users")
    public Result<?> getUsers(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int size,
                             @RequestParam(required = false) Integer status,
                             @RequestParam(required = false) String keyword,
                             HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper.like("nickname", keyword).or().like("openid", keyword));
        }
        queryWrapper.orderByDesc("created_at");
        
        var users = userService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size), queryWrapper);
        return Result.success(users);
    }
    
    @GetMapping("/users/{userId}")
    public Result<?> getUserDetail(@PathVariable Long userId, HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        // 获取用户统计信息
        Map<String, Object> userDetail = new HashMap<>();
        userDetail.put("user", user);
        userDetail.put("totalParseCount", parseRecordService.getTotalParseCount(userId));
        userDetail.put("todayParseCount", parseRecordService.getTodayParseCount(userId));
        
        // 获取最近解析记录
        var recentRecords = parseRecordService.getParseRecords(1, 5, userId, null, null, null, null, null, null);
        userDetail.put("recentRecords", recentRecords.getRecords());
        
        return Result.success(userDetail);
    }

    @PutMapping("/users/{userId}/status")
    public Result<?> updateUserStatus(@PathVariable Long userId,
                                     @RequestBody Map<String, Integer> request,
                                     HttpServletRequest httpRequest) {
        if (!validateAdminToken(httpRequest)) {
            return Result.unauthorized();
        }

        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        Integer status = request.get("status");
        if (status == null || (status != 0 && status != 1)) {
            return Result.error("状态值无效");
        }

        user.setStatus(status);
        userService.updateById(user);

        return Result.success("状态更新成功");
    }

    // ========== 解析记录管理 ==========

    @GetMapping("/records")
    public Result<?> getParseRecords(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int size,
                                   @RequestParam(required = false) Long userId,
                                   @RequestParam(required = false) Integer status,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String endTime,
                                   @RequestParam(required = false) String parseSource,
                                   @RequestParam(required = false) String sourcePlatform,
                                   @RequestParam(required = false) String deviceType,
                                   @RequestParam(required = false) String keyword,
                                   HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }

        LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : null;
        LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : null;

        var records = parseRecordService.getParseRecords(page, size, userId, status, start, end, parseSource, sourcePlatform, deviceType);
        
        // 如果有关键词搜索，需要在Service层实现
        
        return Result.success(records);
    }
    
    @GetMapping("/records/{recordId}")
    public Result<?> getRecordDetail(@PathVariable Long recordId, HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        ParseRecord record = parseRecordService.getById(recordId);
        if (record == null) {
            return Result.error("记录不存在");
        }
        
        return Result.success(record);
    }
    
    @DeleteMapping("/records/{recordId}")
    public Result<?> deleteRecord(@PathVariable Long recordId, HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        ParseRecord record = parseRecordService.getById(recordId);
        if (record == null) {
            return Result.error("记录不存在");
        }
        
        // 软删除
        record.setIsDeleted(1);
        record.setDeletedAt(LocalDateTime.now());
        parseRecordService.updateById(record);
        
        return Result.success("删除成功");
    }
    
    @PostMapping("/records/batch-delete")
    public Result<?> batchDeleteRecords(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        if (!validateAdminToken(httpRequest)) {
            return Result.unauthorized();
        }
        
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) request.get("ids");
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的记录");
        }
        
        for (Long id : ids) {
            ParseRecord record = parseRecordService.getById(id);
            if (record != null) {
                record.setIsDeleted(1);
                record.setDeletedAt(LocalDateTime.now());
                parseRecordService.updateById(record);
            }
        }
        
        return Result.success("批量删除成功");
    }
    
    // ========== 统计分析 ==========

    @GetMapping("/statistics")
    public Result<?> getStatistics(HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }

        try {
            Map<String, Object> stats = new HashMap<>();
            
            long totalUsers = userService.count();
            stats.put("totalUsers", totalUsers);
            
            QueryWrapper<User> activeUserWrapper = new QueryWrapper<>();
            activeUserWrapper.eq("status", 1);
            long activeUsers = userService.count(activeUserWrapper);
            stats.put("activeUsers", activeUsers);
            
            LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            QueryWrapper<ParseRecord> todayWrapper = new QueryWrapper<>();
            todayWrapper.ge("created_at", todayStart);
            long todayParses = parseRecordService.count(todayWrapper);
            stats.put("todayParses", todayParses);
            
            long totalParses = parseRecordService.count();
            QueryWrapper<ParseRecord> successWrapper = new QueryWrapper<>();
            successWrapper.eq("status", 1);
            long successParses = parseRecordService.count(successWrapper);
            double successRate = totalParses > 0 ? (double) successParses / totalParses : 0.0;
            stats.put("successRate", successRate);
            
            Map<String, Object> statusDistribution = new HashMap<>();
            QueryWrapper<ParseRecord> failureWrapper = new QueryWrapper<>();
            failureWrapper.eq("status", 0);
            long failureParses = parseRecordService.count(failureWrapper);
            
            QueryWrapper<ParseRecord> processingWrapper = new QueryWrapper<>();
            processingWrapper.eq("status", 2);
            long processingParses = parseRecordService.count(processingWrapper);
            
            statusDistribution.put("success", successParses);
            statusDistribution.put("failure", failureParses);
            statusDistribution.put("processing", processingParses);
            stats.put("statusDistribution", statusDistribution);
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败");
        }
    }
    
    @GetMapping("/statistics/comprehensive")
    public Result<?> getComprehensiveStatistics(@RequestParam(required = false) String startTime,
                                               @RequestParam(required = false) String endTime,
                                               HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        try {
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : LocalDateTime.now().minusDays(7);
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : LocalDateTime.now();
            
            Map<String, Object> report = statisticsService.getComprehensiveReport(start, end);
            return Result.success(report);
        } catch (Exception e) {
            log.error("获取综合统计失败", e);
            return Result.error("获取综合统计失败");
        }
    }
    
    @GetMapping("/statistics/realtime")
    public Result<?> getRealtimeStatistics(HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        try {
            Map<String, Object> monitoring = statisticsService.getRealtimeMonitoring();
            return Result.success(monitoring);
        } catch (Exception e) {
            log.error("获取实时统计失败", e);
            return Result.error("获取实时统计失败");
        }
    }
    
    @GetMapping("/statistics/user-behavior")
    public Result<?> getUserBehaviorAnalysis(@RequestParam(required = false) String startTime,
                                            @RequestParam(required = false) String endTime,
                                            HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        try {
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : LocalDateTime.now().minusDays(7);
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : LocalDateTime.now();
            
            Map<String, Object> analysis = statisticsService.getUserBehaviorAnalysis(start, end);
            return Result.success(analysis);
        } catch (Exception e) {
            log.error("获取用户行为分析失败", e);
            return Result.error("获取用户行为分析失败");
        }
    }
    
    // ========== 数据导出 ==========
    
    @GetMapping("/export/records")
    public void exportRecords(@RequestParam(required = false) String startTime,
                             @RequestParam(required = false) String endTime,
                             @RequestParam(required = false) String format,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        if (!validateAdminToken(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        
        try {
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : LocalDateTime.now().minusDays(30);
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : LocalDateTime.now();
            String exportFormat = format != null ? format : "csv";
            
            List<Map<String, Object>> data = statisticsService.getExportData(start, end, "records", new HashMap<>());
            
            if ("csv".equalsIgnoreCase(exportFormat)) {
                exportCSV(response, data, "parse_records");
            } else {
                exportJSON(response, data, "parse_records");
            }
            
        } catch (Exception e) {
            log.error("导出解析记录失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    
    @GetMapping("/export/statistics")
    public void exportStatistics(@RequestParam(required = false) String startTime,
                                 @RequestParam(required = false) String endTime,
                                 @RequestParam(required = false) String format,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        if (!validateAdminToken(request)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        
        try {
            LocalDateTime start = startTime != null ? LocalDateTime.parse(startTime) : LocalDateTime.now().minusDays(30);
            LocalDateTime end = endTime != null ? LocalDateTime.parse(endTime) : LocalDateTime.now();
            String exportFormat = format != null ? format : "csv";
            
            List<Map<String, Object>> data = statisticsService.getExportData(start, end, "statistics", new HashMap<>());
            
            if ("csv".equalsIgnoreCase(exportFormat)) {
                exportCSV(response, data, "statistics");
            } else {
                exportJSON(response, data, "statistics");
            }
            
        } catch (Exception e) {
            log.error("导出统计数据失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/trend")
    public Result<?> getTrendData(@RequestParam(defaultValue = "7") int days,
                                 HttpServletRequest request) {
        if (!validateAdminToken(request)) {
            return Result.unauthorized();
        }
        
        try {
            List<Map<String, Object>> trendData = new ArrayList<>();
            
            for (int i = days - 1; i >= 0; i--) {
                LocalDateTime date = LocalDateTime.now().minusDays(i);
                LocalDateTime dayStart = date.withHour(0).withMinute(0).withSecond(0).withNano(0);
                LocalDateTime dayEnd = date.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
                
                QueryWrapper<ParseRecord> dayWrapper = new QueryWrapper<>();
                dayWrapper.between("created_at", dayStart, dayEnd);
                long dayTotal = parseRecordService.count(dayWrapper);
                
                QueryWrapper<ParseRecord> daySuccessWrapper = new QueryWrapper<>();
                daySuccessWrapper.between("created_at", dayStart, dayEnd)
                                .eq("status", 1);
                long daySuccess = parseRecordService.count(daySuccessWrapper);
                
                QueryWrapper<ParseRecord> dayFailureWrapper = new QueryWrapper<>();
                dayFailureWrapper.between("created_at", dayStart, dayEnd)
                                .eq("status", 0);
                long dayFailure = parseRecordService.count(dayFailureWrapper);
                
                Map<String, Object> dayData = new HashMap<>();
                dayData.put("date", date.toLocalDate().toString());
                dayData.put("total", dayTotal);
                dayData.put("success", daySuccess);
                dayData.put("failure", dayFailure);
                
                trendData.add(dayData);
            }
            
            return Result.success(trendData);
        } catch (Exception e) {
            log.error("获取趋势数据失败", e);
            return Result.error("获取趋势数据失败");
        }
    }

    // ========== 系统管理 ==========
    
    @PostMapping("/change-password")
    public Result<?> changePassword(@RequestBody Map<String, String> request, HttpServletRequest httpRequest) {
        if (!validateAdminToken(httpRequest)) {
            return Result.unauthorized();
        }
        
        String currentPassword = request.get("currentPassword");
        String newPassword = request.get("newPassword");
        
        if (currentPassword == null || newPassword == null) {
            return Result.error("当前密码和新密码不能为空");
        }
        
        if (newPassword.length() < 6) {
            return Result.error("新密码长度至少6位");
        }
        
        try {
            String token = httpRequest.getHeader("Authorization").substring(7);
            String adminId = jwtUtil.getSubjectFromToken(token);
            Admin admin = adminService.getById(adminId);
            
            if (admin == null) {
                return Result.error("管理员不存在");
            }
            
            if (!"admin123".equals(currentPassword)) {
                return Result.error("当前密码错误");
            }
            
            admin.setPassword(newPassword);
            adminService.updateById(admin);
            
            return Result.success("密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error("修改密码失败");
        }
    }
    
    @PostMapping("/system/cleanup")
    public Result<?> systemCleanup(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        if (!validateAdminToken(httpRequest)) {
            return Result.unauthorized();
        }
        
        try {
            Integer days = (Integer) request.get("days");
            if (days == null || days < 1) {
                return Result.error("请指定有效的清理天数");
            }
            
            LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
            
            // 软删除过期记录
            QueryWrapper<ParseRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.lt("created_at", cutoffTime);
            queryWrapper.eq("is_deleted", 0);
            
            List<ParseRecord> records = parseRecordService.list(queryWrapper);
            for (ParseRecord record : records) {
                record.setIsDeleted(1);
                record.setDeletedAt(LocalDateTime.now());
                parseRecordService.updateById(record);
            }
            
            return Result.success("清理完成，共处理 " + records.size() + " 条记录");
        } catch (Exception e) {
            log.error("系统清理失败", e);
            return Result.error("系统清理失败");
        }
    }

    // ========== 私有方法 ==========

    private boolean validateAdminToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return false;
        }

        token = token.substring(7);
        if (!jwtUtil.validateToken(token)) {
            return false;
        }

        String userType = jwtUtil.getUserTypeFromToken(token);
        return "admin".equals(userType);
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
    
    private void exportCSV(HttpServletResponse response, List<Map<String, Object>> data, String filename) throws IOException {
        response.setContentType("text/csv;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename + "_" + 
                          LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".csv");
        
        PrintWriter writer = response.getWriter();
        
        if (!data.isEmpty()) {
            // 写入表头
            Map<String, Object> firstRow = data.get(0);
            writer.println(String.join(",", firstRow.keySet()));
            
            // 写入数据
            for (Map<String, Object> row : data) {
                List<String> values = new ArrayList<>();
                for (Object value : row.values()) {
                    values.add(value != null ? value.toString() : "");
                }
                writer.println(String.join(",", values));
            }
        }
        
        writer.flush();
        writer.close();
    }
    
    private void exportJSON(HttpServletResponse response, List<Map<String, Object>> data, String filename) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename + "_" + 
                          LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".json");
        
        PrintWriter writer = response.getWriter();
        // 简单的JSON输出，实际项目中应该使用JSON库
        writer.println("[");
        for (int i = 0; i < data.size(); i++) {
            writer.print("  ");
            writer.print(data.get(i).toString()); // 简化的JSON输出
            if (i < data.size() - 1) {
                writer.println(",");
            } else {
                writer.println();
            }
        }
        writer.println("]");
        
        writer.flush();
        writer.close();
    }
}